import string
import random

from PyQt6.QtGui import QIntValidator
from PyQt6.QtWidgets import QLabel, QHBoxLayout, QVBoxLayout, QLineEdit, QCheckBox, QPushButton, QTextEdit

from utils.reference import AbstractCustomDialog, copy_to_clipboard, qt_connect


class RandomDialog(AbstractCustomDialog):
    def __init__(self):
        super().__init__()

        self.setWindowTitle('随机')

        label_string_len = QLabel(self)
        label_string_len.setText('长度')

        self.edit_string_len = QLineEdit(self)
        self.edit_string_len.setValidator(QIntValidator())
        self.edit_string_len.setPlaceholderText('>=6, 默认6')

        self.active_number = QCheckBox(self)
        self.active_number.setText('数字')

        self.active_symbol = QCheckBox(self)
        self.active_symbol.setText('符号')

        self.btn_copy = QPushButton('复制', self)
        qt_connect(self.btn_copy.clicked, self.copy_content)

        self.btn_gen = QPushButton('生成', self)
        qt_connect(self.btn_gen.clicked, self.generator_string)

        self.edit_text = QTextEdit(self)
        self.edit_text.setReadOnly(True)

        hbox1 = QHBoxLayout()
        hbox1.addWidget(label_string_len)
        hbox1.addWidget(self.edit_string_len)
        hbox1.addWidget(self.active_number)
        hbox1.addWidget(self.active_symbol)
        hbox1.addStretch(1)

        hbox2 = QHBoxLayout()
        hbox2.addWidget(self.btn_gen)
        hbox2.addWidget(self.btn_copy)

        vbox = QVBoxLayout()
        vbox.addLayout(hbox1)
        vbox.addLayout(hbox2)
        vbox.addWidget(self.edit_text)

        self.setLayout(vbox)

    def copy_content(self):
        text = self.edit_text.toPlainText()
        copy_to_clipboard(text)

    def generator_string(self):
        chars = string.ascii_letters
        if self.active_number.isChecked():
            chars += string.digits
        if self.active_symbol.isChecked():
            chars += string.punctuation

        length = 6
        if t := self.edit_string_len.text():
            length = int(t)

        result = ''.join(random.choices(chars, k=length))
        self.edit_text.setText(result)
